#!/bin/bash
#
# Simple CPU loader by Vladislav Belogrudov
# vlad.belogrudov@gmail.com
# 



trap 'kill -9 `jobs -p` > /dev/null 2>&1; exit 1' INT

nproc=`grep processor /proc/cpuinfo | wc -l`
echo "number of CPUs = $nproc"

while true
do
    # generate random time and load between 1 and 100
    mylimit=`head -30 /dev/urandom | tr -dc "0123456789" | head -c3`
    mylimit=$((mylimit % 100))
    mytime=`head -30 /dev/urandom | tr -dc "0123456789" | head -c3`   
    mytime=$((mytime % 60))

    echo "running at $mylimit% for $mytime seconds"
    [ $mylimit -eq 0 ] && sleep $mytime && continue
    for i in `seq 1 $nproc` 
    do
        echo "spawning load #$i"
        cat /dev/urandom  > /dev/null 2>&1 &
        cpulimit -l $mylimit -p $! > /dev/null 2>&1 &
    done
    sleep $mytime
    for pid in `jobs -p 2>/dev/null`
    do
        kill -9 $pid > /dev/null 2>&1
    done
done
